use crate::model::db;
use crate::model::request::{TopicInfo, TopicSearch};
use crate::model::response::{TopicInfoRes, TopicList};
use sqlx::{self};

// 创建 topic
pub async fn create_topic(data: &TopicInfo) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    sqlx::query("INSERT INTO tb_topic (type, name, topic_text, message, remark, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())")
        .bind(&data.r#type)
        .bind(&data.name)
        .bind(&data.topic_text)
        .bind(&data.message)
        .bind(&data.remark)
        .execute(pool)
        .await?;
    Ok(())
}

// 修改device
pub async fn edit_topic(data: &TopicInfo) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let sql_text = "UPDATE tb_topic SET type = ?, name = ?, topic_text = ?, message = ?, remark = ?, updated_at = NOW() WHERE id = ?";
    let res = sqlx::query(&sql_text)
        .bind(&data.r#type)
        .bind(&data.name)
        .bind(&data.topic_text)
        .bind(&data.message)
        .bind(&data.remark)
        .bind(&data.id)
        .execute(pool)
        .await;

    match res {
        Ok(i) => println!("ok {:#?}", i),
        Err(e) => println!("err {:#?}", e),
    }
    Ok(())
}

// 详情
pub async fn topic_detail(id: u64) -> Result<TopicInfoRes, sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let res = sqlx::query_as::<_, TopicInfoRes>("SELECT * FROM tb_topic WHERE id=?")
        .bind(id)
        .fetch_one(pool)
        .await;
    match res {
        Ok(i) => {
            println!("{:#?}", i);
            Ok(i)
        }
        Err(e) => {
            println!("{:#?}", e);
            Err(e)
        }
    }
}

// 删除 topic
pub async fn delete_topic(id: u64) -> Result<(), sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let _res = sqlx::query("DELETE FROM tb_topic WHERE id=?")
        .bind(id)
        .execute(pool)
        .await?;
    Ok(())
}

// 获取 topic list
pub async fn get_topic_list(data: &TopicSearch) -> Result<TopicList, sqlx::Error> {
    let pool = db::get_pool().unwrap();
    let offset = (data.page - 1) * data.page_size;

    // 第一步：构建最基础的查询
    let mut query =
        "SELECT id,type,name,topic_text,message,remark,created_at,updated_at FROM tb_topic"
            .to_string();

    // 构建搜索条件
    let mut conditions = Vec::new();

    if let Some(id) = &data.id {
        conditions.push(format!("id = '{}'", id));
    }

    if let Some(name) = &data.name {
        conditions.push(format!("name LIKE '%{}%'", name));
    }

    if let Some(r#type) = &data.r#type {
        conditions.push(format!("type LIKE '%{}%'", r#type));
    }

    if let Some(topic_text) = &data.topic_text {
        conditions.push(format!("topic_text LIKE '%{}%'", topic_text));
    }

    if let Some(message) = &data.message {
        conditions.push(format!("message LIKE '%{}%'", message));
    }

    // 添加搜索条件到查询语句
    if !conditions.is_empty() {
        query.push_str(" WHERE ");
        query.push_str(&conditions.join(" AND "));
    }

    // 添加排序和分页限制
    query.push_str(" ORDER BY created_at DESC LIMIT ? OFFSET ?");

    println!("sql: {}", query);
    // 执行查询
    let topic_list = sqlx::query_as::<_, TopicInfoRes>(&query)
        .bind(data.page_size)
        .bind(offset)
        .fetch_all(pool)
        .await?;

    // 获取总条数
    let count_query = format!(
        "SELECT COUNT(*) as total FROM tb_topic {}",
        if !conditions.is_empty() {
            format!("WHERE {}", conditions.join(" AND "))
        } else {
            "".to_string()
        }
    );
    let count_result: (Option<i64>,) = sqlx::query_as(count_query.as_str()).fetch_one(pool).await?;
    let count = count_result.0.unwrap_or(0); // 空结果处理

    let res = TopicList {
        list: topic_list,
        total: count,
    };

    Ok(res)
}
